<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>new service</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="public/layui/css/layui.css" media="all">
    <style>
        .layui-form-item .layui-form-checkbox[lay-skin=primary] {
            margin-top: 0px;
        }

        .layui-tab {
            margin: 0;
        }

        th[data-field=id],
        td[data-field=id] {
            display: none;
        }
    </style>
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body style="padding-left: 0px;overflow:hidden">
<div class="layui-tab layui-tab-brief" lay-filter="instanceTab">
    <ul class="layui-tab-title">
        <li lay-id="1">新增</li>
        <li class="layui-this" lay-id="2">实例列表</li>

    </ul>
    <div class="layui-tab-content">
        <div class="layui-tab-item layui-form layui-form-pane">
            <div class="layui-form-item">
                <label class="layui-form-label">新增方式</label>
                <div class="layui-input-inline">
                    <select name="createMode" id="createMode" lay-filter="createMode" lay-verify="required"
                            lay-search="">
                        <option value="1">自动新增</option>
                        <option value="2">手工新增</option>
                    </select>

                </div>

            </div>
            <div class="layui-form-item" style="display:none" name="manualScale">
                <label class="layui-form-label">选择机器</label>
                <div class="layui-input-inline">
                    <select name="machineId" id="machineId" lay-filter="machineId" lay-verify="machineId" lay-search="">
                        <option value=""><b>选择指定机器</b></option>
                    </select>

                </div>
            </div>
            <div class="layui-form-item" style="display:none" name="manualScale">
                <label class="layui-form-label">实例端口</label>
                <div class="layui-input-inline">
                    <input type="text" name="port" lay-verify="port" autocomplete="off" placeholder="端口"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-form-item" name="autoScale">
                <label class="layui-form-label">实例个数</label>
                <div class="layui-input-inline">
                    <input type="text" id="insCount" name="insCount" lay-verify="number|insCount" autocomplete="off"
                           placeholder="端口"
                           class="layui-input" value="1">

                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">权重</label>
                <div class="layui-input-inline">
                    <input type="text" id="weight" name="weight" lay-verify="number|weight" autocomplete="off"
                           placeholder="权重"
                           class="layui-input" value="10">
                </div>
                <div class="layui-form-mid layui-word-aux">默认10</div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">分支镜像</label>
                <div class="layui-input-block">
                    <input type="text" id="repoId" name="repoId" style="display:none"><input type="text" id="repoInfo"
                                                                                             name="repoInfo"
                                                                                             lay-verify="repoInfo"
                                                                                             autocomplete="off"
                                                                                             placeholder="默认主分支最新版本"
                                                                                             class="layui-input"
                                                                                             style="display:inline;width:320px"
                                                                                             disabled="true">

                    <button class="layui-btn layui-btn-xs layui-btn-normal" id="selectBranch">选择</button>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">后续事件</label>
                <div class="layui-input-inline" style="width:200px">
                    <select name="followUpState" lay-filter="followUpState">
                        <option value="0" selected="">不开机</option>
                        <option value="1">开机</option>
                        <option value="2">静默开机</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item" style="margin: 0;text-align:center;">
                <button class="layui-btn layui-btn-sm" id="add-instance" lay-submit="" lay-filter="add-instance">立即提交
                </button>
            </div>

        </div>
        <script type="text/html" id="tableBar">
            <a class="layui-btn layui-btn-xs oka-btn-radius" lay-event="detail">详细</a>
        </script>
        <script type="text/html" id="machineTpl">
            <a href="javascript:;" data-id="{{ d.machineId }}" class="layui-table-link" name="machine-btn"
               target="_blank">{{ d.machineInfo }}</a>
        </script>
        <script type="text/html" id="stateTpl">
            {{#  if(d.processing == true){ }}
            <i class="layui-icon layui-anim layui-anim-rotate layui-anim-loop" label="aaa">&#xe63d;</i>
            {{#  } else { }}
            {{#  if(d.state == 0){ }}
            <span style="color: #ccc;">关机</span>
            {{#  } else if(d.state == 1) { }}
            <span style="color:#00a65a;">运行</span>
            {{#  } else if(d.state == 2) { }}
            <span style="color:#FFB800;">暂停</span>
            {{#  } }}
            {{#  } }}
        </script>

        <div class="layui-tab-item  layui-show">
            <div class="layui-form layui-form-pane" id="ability-form">
                <div class="layui-form-item layui-form-text" style="width:100%;margin-bottom: 0">
                    <div id="panel-btn">
                        <div style="display:inline">
                            <button class="layui-btn layui-btn-sm " id="start-instance">启动</button>
                            <button class="layui-btn layui-btn-sm " id="silentStart-instance">静默启动</button>
                            <button class="layui-btn layui-btn-sm layui-btn-warm" id="resume-instance">恢复</button>
                            <button class="layui-btn layui-btn-sm layui-btn-warm" id="pause-instance">暂停</button>
                        </div>
                        <div style="display:inline;float:right">
                            <button class="layui-btn layui-btn-sm layui-btn-normal" id="switch-instance">切换</button>
                            <button class="layui-btn layui-btn-sm layui-btn-danger" id="restart-instance">重启</button>
                            <button class="layui-btn layui-btn-sm layui-btn-danger" id="shutdown-instance">关机</button>
                            <button class="layui-btn layui-btn-sm layui-btn-danger" id="forceShutdown-instance">强制关机</button>
                            <button class="layui-btn layui-btn-sm layui-btn-danger" id="del-instance">删除</button>
                        </div>
                    </div>
                    <div class="layui-input-block">
                        <table class="layui-table" id="layui-table" lay-data="{even:true, page: {layout: ['prev', 'page', 'next', 'skip','count'] }, height:338, id:'instances'}"
                               lay-filter="instances">
                            <thead>
                            <tr>
                                <th lay-data="{type:'numbers'}"></th>
                                <th lay-data="{type:'checkbox'}"></th>
                                <th lay-data="{field:'id', width:1, minWidth:1}"></th>
                                <th lay-data="{field:'machineInfo', minWidth:90}">机器</th>
                                <th lay-data="{field:'port', width:70}">端口</th>
                                <th lay-data="{field:'branch', sort:true, align:'center',width:80}">分支</th>
                                <th lay-data="{field:'version',sort:true, width:215}">版本</th>
                                <th lay-data="{field:'stateText',sort:true, align:'center', width:72, templet: '#stateTpl'}">
                                    状态
                                </th>
                                <th lay-data="{field:'toolbar',width:64,toolbar:'#tableBar'}">详细</th>
                                <!-- 运行 挂起  关闭-->
                            </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>


<script src="public/layui/layui.js" charset="utf-8"></script>
<script src="js/jquery-3.2.1.js"></script>
<script src="js/loader.js"></script>
<script>
    var serviceId = location.hash.substring(1);

    layui.use(['form', 'laydate', 'oka', 'table','element'], function () {
        var form = layui.form
            , layer = layui.layer
            , laydate = layui.laydate
            , table = layui.table
            , oka = layui.oka;

        //自定义验证规则
        oka.loading.open();
        parent.oka.parentIndex = parent.layer.index;
        $.ajax({
            url: "/admin/machine"
            , type: "GET"
            , dataType: "json"
            , async: true
            , success: function (res) {
                oka.loading.close();
                //obj = null;
                var dom = $("#machineId");
                for (var i = 0, len = res.data.length; i < len; i++) {
                    var option = document.createElement("option");
                    var item = "<option value='" + res.data[i]["id"] + "'>" + res.data[i]["name"] + "</option>";
                    dom.append(item);
                }
                form.render("select");
                dom = null;

            }
        });
        function getStateDesc(state, processing) {
            if(processing == true) {
                return '<i class="layui-icon layui-anim layui-anim-rotate layui-anim-loop" label="aaa">&#xe63d;</i>';
            }
            state = parseInt(state);
            switch(state) {
                case 0:
                    return '<span style="color: #ccc;">关机</span>';
                case 1:
                    return '<span style="color: #00a65a;">运行</span>';
                    beak;
                case 2:
                    return '<span style="color: #FFB800;">暂停</span>';
                    beak;
                case 3:
                    return '<span style="color: #FFB800;">初始化</span>';
                    beak;
            }
        }
        oka.loading.open();
        table.reload('instances', {
            url: '/admin/instances/'+serviceId
            ,where: {}
            ,done:function() {
                oka.loading.close();

                function refresh() {
                    var data = table.cache.instances.slice();
                    console.log(data)
                    for (var i = 0, l = data.length; i < l; i++) {
                        (function (i) {

                            var addr = data[i].machineAddr;
                            if (!addr) return;
                            addr = addr.substring(0, addr.indexOf(":") + 1) + data[i].port;
                            //alert(data[i].state)
                            $.ajax({
                                url: "/node/instance/health?ip=" + addr + (data[i].state == 3 ? ("&id=" + data[i].id) : "")
                                , type: "GET"
                                , async: true
                                , success: function (res) {
                                    //初始化
                                    if (data[i].state == 3) {
                                        data[i].state = res;
                                        if(res == 1 || res == 2) {
                                            data[i].processing = true;
                                        }

                                    } else {
                                        if (data[i].processing != undefined) {
                                            if (res == data[i].state || (res == 1 && data[i].state == 2)) {
                                                delete data[i].processing;
                                            }
                                        } else {
                                            if (data[i].state != 2) {
                                                if (res != data[i].state) {

                                                    data[i].processing = true;
                                                }
                                            }
                                        }
                                    }
                                    oka.table.refresh("instances", i, ['stateText'],[getStateDesc(data[i].state, data[i].processing)]);
                                    /*
                                    table.reload("instances", {
                                        data: data
                                    })
                                    */
                                }
                            });
                        })(i);
                    }
                }

                refresh();
                oka.page.timer = window.setInterval(function () {
                    refresh();
                }, 16000);

            }
        });
        /*
        $.ajax({
            url: "/admin/instances/" + serviceId
            , type: "GET"
            , dataType: "json"
            , async: true
            , success: function (res) {
                oka.loading.close();
                var data = res.data;

                table.reload("instances", res)

                function fresh() {
                    var data = table.cache.instances.slice();
                    console.log(data)
                    for (var i = 0, l = data.length; i < l; i++) {
                        (function (i) {

                            var addr = data[i].machineAddr;
                            if (!addr) return;
                            addr = addr.substring(0, addr.indexOf(":") + 1) + data[i].port;
                            $.ajax({
                                url: "/node/instance/health?ip=" + addr + (data[i].state == 3 ? ("&id=" + data[i].id) : "")
                                , type: "GET"
                                , async: true
                                , success: function (res) {
                                    //alert(res + "===" + i);
                                    if (data[i].state == 3) {
                                        data[i].state = res;
                                    } else {
                                        if (data[i].processing != undefined) {
                                            if (res == data[i].state) {
                                                delete data[i].processing;
                                            }
                                        } else {
                                            if (data[i].state != 2) {
                                                if (res != data[i].state) {
                                                    data[i].processing = true;
                                                }
                                            }
                                        }
                                    }

                                    table.reload("instances", {
                                        data: data
                                    })
                                }
                            });
                        })(i);
                    }
                }

                fresh();
                window.setInterval(function () {
                    fresh();
                }, 160000);
            }
        });
        */
        form.verify({
            port: function (value) {
                if ($("#createMode").val() == 2) {
                    if (value == "") {
                        return "端口不能为空";
                    }
                    if (isNaN(value)) {
                        return "必须是数字";
                    }
                    if (value > 65565 || value < 0) {
                        return '端口范围在0-65565范围内';
                    }
                }

            },
            machineId: function (value) {
                if ($("#createMode").val() == 2) {
                    if (value == "") {
                        return "请选择机器";
                    }

                }
            },
            insCount: function (value) {
                if ($("#createMode").val() == 1) {
                    if (value == "") {
                        return "实例个数不能为空";
                    }
                    if (isNaN(value)) {
                        return "必须是数字";
                    }
                    if (value > 10) {
                        return '每次创建实例个数，上限10';
                    }
                }

            }
        });


        form.on('submit(add-instance)', function (data) {
            oka.loading.open();
            data.field.serviceName = serviceId;
            var url = "/admin/instance", createMode = $("#createMode").val();

            if (createMode == 1) {
                url = url + "?mode=1&count=" + $("#insCount").val();
            }

            var repoInfo = data.field.repoInfo, ix = repoInfo.indexOf(":");
            if (ix > -1) {
                data.field.branch = repoInfo.substring(0, ix);
                data.field.version = repoInfo.substring(ix + 1);
            }
            $.ajax({
                url: url
                , type: "POST"
                , contentType: "application/json"
                , dataType: "json"
                , async:true
                , data: JSON.stringify(data.field)
                , success: function (res) {
                    oka.loading.close();
                    if (res.code == "0") {
                        layer.msg('操作失败!!！'+res.desc, {
                            offset: "t",
                            anim: 6
                        });

                    } else {
                        table.reload("instances");
                        layer.msg('操作成功', {
                            time: 500
                        });
                        layui.element.tabChange('instanceTab', '2');
                    }
                    obj = null;

                }
            });
            /*
            var d = table.cache.instances.slice();
            d.push({
                machine:($("[name='machine']").find("option:selected").text()),
                port:"65566",
                status:'停止'
            });
            console.log(table)
            table.reload("instances", {
                data:d
            })
            */

            return false;
        });
        $("#selectBranch").on('click', function (e) {
            parent.layer.open({
                type: 2,
                title: "选择jar应用",
                content: ["repo.html#" + serviceId, 'yes'],
                area: ['800px', '480px'],
                end: function () {
                }
            });
            return false;
        });
        $("#panel-btn").on('click', function (e) {
            var id = e.target.id;

            if (id.indexOf("-instance") > -1) {
                var checkStatus = table.checkStatus('instances')
                    , selData = checkStatus.data;
                if (selData.length == 0) {
                    layer.msg('需要选记录进行操作', {
                        time: 600
                    });
                    return false;
                }

                id = id.substring(0, id.indexOf("-instance"));

                switch (id) {
                    case 'start':
                    case 'silentStart':
                    case 'shutdown':
                    case 'forceShutdown':
                    case 'pause':
                    case 'restart':
                    case 'resume':

                        /*
                        for(var i = 0, l = checkStatus.data.length; i < l; i++) {
                            ids.push(checkStatus.data[i].id);
                            ids[checkStatus.data[i].id] = 1;
                        }
                        */
                        oka.loading.open();
                        var insArr = [];
                        var data = {"action": id, "data": insArr};
                        for (var i = 0, l = selData.length; i < l; i++) {
                            insArr.push(selData[i].id);
                        }
                        $.ajax({
                            url: "node/process"
                            , type: "POST"
                            , contentType: "application/json"
                            , async: true
                            , dataType: "json"
                            , data: JSON.stringify(data)
                            , error: function() {
                                oka.loading.close();
                                layer.msg('连接异常，请查看console', {
                                    offset: "t",
                                    anim: 6
                                });
                            }
                            , success: function (res) {
                                oka.loading.close();

                                var d = table.cache.instances.slice();
                                var len = res.length, fail = 0;
                                for (var i = 0; i < len; i++) {
                                    var item = res[i];
                                    if (item != "0") {
                                        for (var j = 0, k = d.length; j < k; j++) {
                                            if(d[j].id == insArr[i]) {
                                                if (id == "start" || id == "silentStart" || id == "shutdown" || id == "forceShutdown") {
                                                    d[j].state = (id == "start" ? 1 :(id == "silentStart"?"2":"0"));
                                                    d[j].processing = true;
                                                    item = "-1";
                                                } else if (id == "pause") {
                                                    item = d[j].state = 2;
                                                } else if (id == "resume") {
                                                    item = d[j].state = 1;
                                                }
                                                oka.table.refresh("instances", j, ['stateText']
                                                    , [getStateDesc(d[j].state,d[j].processing)]);
                                                break;
                                            }
                                        }
                                    } else {
                                        fail++;
                                    }
                                }

                                if(fail > 0) {
                                    layer.msg('失败：'+fail, {
                                        offset: "t",
                                        anim: 6
                                    });
                                } else {
                                    layer.msg('操作成功', {
                                        time: 600
                                    });
                                }

                                /*
                                layer.msg('操作失败!!！', {
                                    offset: "t",
                                    anim: 6
                                });
                                */


                            }
                        });
                        break;
                    case 'del':
                        //console.log(checkStatus);
                        var ids = [];
                        for (var i = 0, l = checkStatus.data.length; i < l; i++) {
                            ids.push(checkStatus.data[i].id);
                            ids[checkStatus.data[i].id] = 1;
                        }
                        layer.confirm('确认要删除这些实例？', function (index) {
                            oka.loading.open();
                            $.ajax({
                                url: "/admin/instance/1?ids=" + ids.join("_")
                                , type: "DELETE"
                                , async: true
                                , success: function (res) {
                                    oka.loading.close();
                                    if (res.bizCode == "0") {
                                        layer.msg('操作失败!!！', {
                                            offset: "t",
                                            anim: 6
                                        });

                                    } else {
                                        layer.msg('操作成功', {
                                            time: 600
                                        });

                                        var d = table.cache.instances.slice();
                                        console.log(d)
                                        console.log(ids)
                                        for (var i = d.length - 1; i > -1; i--) {
                                            if (ids[d[i].id] == 1) {
                                                d.splice(i, 1);
                                            }
                                        }
                                        table.reload("instances", {
                                            data: d
                                        });
                                        layer.close(index);
                                    }

                                    obj = null;

                                }
                            });
                        });

                        break;


                }

            }
        })
        form.on('select(createMode)', function (data) {

            if (data.value == "1") {
                $("[name=manualScale]").hide();
                $("[name=autoScale]").show();
            } else {
                $("[name=manualScale]").show();
                $("[name=autoScale]").hide();
            }

        });
        $(document).on('click', '.layui-table>tbody>tr', function (e) {
            //console.log($(this)[0])
            if (e.target.name == "machine-btn") {
                var name = e.target.getAttribute("data-id");
                layer.open({
                    type: 2,
                    title: "添加新的实例",
                    content: ["machine.html#" + name, 'yes'],
                    area: ['700px', '480px'],
                    end: function () {
                        if (oka.page.ret != undefined) {
                            var ret = JSON.parse(oka.page.ret);
                            delete oka.page["ret"];
                            obj.update(ret);
                            console.log(ret);
                            if (ret.status == "on") {
                                obj.tr[0].querySelector('[name="status"]').setAttribute("checked", true);
                            } else {
                                obj.tr[0].querySelector('[name="status"]').removeAttribute("checked");
                            }


                            form.render();
                        }

                    }
                });
            }

        })
    });
</script>

</body>
</html>